import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { Select, Button, Table, Input, DatePicker, message } from "antd";
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
} from "@ant-design/icons";
import { text_check, post_axios } from "../../utils";
import EditUser from "./edit_user";

export default function User(props) {
  const { t } = useTranslation();
  const { RangePicker } = DatePicker;
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  // 获取角色级别
  const [role_action_array, setRole_action_array] = useState([]);
  // 级别拆解对象
  const [grade_object, setGrade_object] = useState({});
  // 查询菜单权限及级别数据
  const get_role_action_menu = async () => {
    let upMsg = {
      op_type: "action",
    };
    let res = await post_axios("login_get_menu", "menu", upMsg);
    if (!res) return;
    let rows = res.data.array_role;
    //   级别对应中英文对象
    let grade_map_arr = {};
    let role_action_array = [
      {
        label: t("system_manager.all"),
        value: "",
        key: "*",
      },
    ];
    rows.forEach((ele) => {
      grade_map_arr[`${ele.role_grade}`] = text_check(ele);
      role_action_array.push({
        key: ele.role_grade,
        label: text_check(ele),
        value: ele.role_grade,
      });
    });
    setRole_action_array(role_action_array);
    setGrade_object(grade_map_arr);
  };

  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);
  const [company_scope, setCompany_scope] = useState("now");
  const [username_search, setUsername_search] = useState("");
  const [role_grade, setRole_grade] = useState("");
  const [user_list, setUser_list] = useState([]);

  const company_scope_list = [
    {
      label: t("system_manager.current_selected"),
      key: "now",
      value: "now",
    },
    {
      label: t("system_manager.all"),
      key: "*",
      value: "*",
    },
  ];

  const search_data = () => {
    setPage(1);
    initData(1);
  };

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: company_scope == "now" ? local_company_object.id : "",
      company: company_scope == "now" ? local_company_object.company : "",
      username_search: username_search,
      role_grade: role_grade,
      op_type: "list_user",
    };
    setSpinning(true);
    let res = await post_axios("user_manager", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setUser_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: t("system_manager.login_name"),
      dataIndex: "username",
      align: "center",
    },
    {
      title: t("system_manager.name"),
      align: "center",
      render: (_, record) => (
        <>
          <div>{record.name}</div>
          {session_company === "mg" ? <div>{record.last_name}</div> : ""}
        </>
      ),
    },
    {
      title: "Email",
      align: "center",
      render: (_, record) => (
        <>
          {record.tel ? <div>***{record.tel.substring(7)}</div> : ""}
          {record.email ? <div>***{record.email.substring(7)}</div> : ""}
        </>
      ),
    },
    {
      title: t("system_manager.role_name_new"),
      dataIndex: "role_name",
      align: "center",
    },
    {
      title: t("system_manager.role_grade_new"),
      align: "center",
      render: (_, record) => <>{grade_object[`${record.role_grade}`]}</>,
    },
    {
      title: t("system_manager.company"),
      dataIndex: "company",
      align: "center",
    },
    {
      title: t("system_manager.data_time_section"),
      align: "center",
      render: (_, record) => (
        <>
          {record.datatime1 ? <div>{record.datatime1}</div> : ""}
          {record.datatime2 ? <div>{record.datatime2}</div> : ""}
        </>
      ),
    },
    {
      title: t("system_manager.last_login_time"),
      align: "center",
      render: (_, record) => (
        <>
          {record.utime ? <div>{record.utime.substring(0, 10)}</div> : ""}
          {record.utime ? <div>{record.utime.substring(11, 20)}</div> : ""}
        </>
      ),
    },
    {
      title: t("system_manager.create_time"),
      align: "center",
      render: (_, record) => (
        <>
          {record.ctime ? <div>{record.ctime.substring(0, 10)}</div> : ""}
          {record.ctime ? <div>{record.ctime.substring(11, 20)}</div> : ""}
        </>
      ),
    },
  ];
  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  const initData = (page, rows) => {
    setClicked_username("");
    setClicked_user_obj([]);
    setUser_com_list([]);
    setUser_kind_list([]);
    getData(page, rows);
  };

  // 用户数据行点击
  const [clicked_username, setClicked_username] = useState("");
  const [clicked_user_obj, setClicked_user_obj] = useState({});
  const [user_com_list, setUser_com_list] = useState();
  const [user_kind_list, setUser_kind_list] = useState();

  const user_row_click = (row) => {
    setClicked_username(JSON.parse(JSON.stringify(row)).username);
    setClicked_user_obj(row);
    get_user_power(row);
  };

  // 点击后获取用户相关权限信息
  const get_user_power = async (row) => {
    // setUser_com_list([]);
    // setUser_kind_list([]);
    setSpinning(true);
    switch (row.role_grade) {
      case 62:
      case 63:
      case 64:
        // 获取用户选择的组织
        let com_upMsg = {
          company: local_company_object.company,
          company_id: local_company_object.id,
          op_type: "list_com_id",
          username: row.username,
        };
        let com_res = await post_axios("user_manager", "m_query", com_upMsg);
        setUser_com_list(com_res.data_rows.rows);
        break;
      case 70:
        // 获取用户选择的商户
        let mch_upMsg = {
          company: local_company_object.company,
          company_id: local_company_object.id,
          op_type: "list_mch",
          username: row.username,
        };
        let mch_res = await post_axios("user_manager", "m_query", mch_upMsg);
        setUser_com_list(mch_res.data_rows.rows);
        break;
      case 80:
        // 获取用户选择的线路
        let circuit_upMsg = {
          company: local_company_object.company,
          company_id: local_company_object.id,
          op_type: "list_circuit",
          username: row.username,
        };
        let circuit_res = await post_axios(
          "user_manager",
          "m_query",
          circuit_upMsg
        );
        setUser_com_list(circuit_res.data_rows.rows);
        break;
      default:
        break;
    }
    if (row.role_grade > 61) {
      //获取商品库
      let upMsg = {
        company: local_company_object.company,
        company_id: local_company_object.id,
        op_type: "list_goods_kind",
        username: row.username,
      };
      let res = await post_axios("user_manager", "m_query", upMsg);
      setUser_kind_list(res.data_rows.rows);
    }
    setSpinning(false);
  };

  // 获取角色列表
  const [role_list, setRole_list] = useState([]);
  const get_role_data = async () => {
    let upMsg = {
      op_type: "list_role",
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("role_manager", "m_query", upMsg);
    setRole_list(res.data_rows.rows);
  };

  // 获取商品库列表
  const [kind_list, setKind_list] = useState();
  const get_kind_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_goods_kind",
      username: username,
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setKind_list(res.data_rows.rows);
  };
  // 获取商户列表
  const [mch_list, setMch_list] = useState();
  const get_mch_data = async () => {
    let upMsg = {
      company: local_company_object.company,
      company_id: local_company_object.id,
      op_type: "list_mch",
      username: username,
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setMch_list(res.data_rows.rows);
  };

  // 获取线路列表
  const [circuit_list, setCircuit_list] = useState();
  const get_circuit_data = async () => {
    let upMsg = {
      company: local_company_object.company,
      company_id: local_company_object.id,
      op_type: "list_route",
      username: username,
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCircuit_list(res.data_rows.rows);
  };

  // 获取组织列表
  const [com_list, setCom_list] = useState();
  const get_com_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
      op_type: "list_com_id",
    };
    let res = await post_axios("admin_oneself", "m_query", upMsg);
    if (!res) return;
    setCom_list(res.data_rows.rows);
  };

  // 添加/修改
  const [edit_type, setEdit_type] = useState("");
  const [edit_user_show, setEdit_user_show] = useState(false);
  const [edit_user_title, setEdit_user_title] = useState("");
  const edit_user_dialog_show = async (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEdit_user_show(true);
      setEdit_user_title(t("common.add") + t("system_manager.admin"));
    } else {
      if (clicked_username === "") {
        message.warning({
          content: t("system_manager.choose_one_user"),
        });
        return;
      }
      setEdit_user_show(true);
      setEdit_user_title(t("common.change") + t("system_manager.admin"));
    }
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("user_manager")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
    });
    get_role_action_menu();
    get_role_data();
    get_kind_data();
    if (user_grade !== 80) {
      get_mch_data();
    }
    if (user_grade !== 70) {
      get_circuit_data();
    }
    if (user_grade < 70) {
      get_com_data();
    }
  }, []);
  return (
    <>
      <div className="user_manager modules">
        <div className="screen_ipt">
          <div className="ipt_box normal_title">
            <div className="ipt_box_title">{t("system_manager.company")}</div>
            <Select
              size="small"
              placeholder=" "
              options={company_scope_list}
              value={company_scope}
              onChange={(value) => setCompany_scope(value)}
            />
          </div>
          <div className="ipt_box normal_title">
            <div className="ipt_box_title">
              {t("system_manager.role_grade_new")}
            </div>
            <Select
              size="small"
              placeholder=" "
              options={role_action_array}
              value={role_grade}
              onChange={(value) => setRole_grade(value)}
            />
          </div>

          <div className="ipt_box normal_title">
            <div className="ipt_box_title">
              {t("system_manager.login_account")}
            </div>
            <Input
              placeholder=" "
              value={username_search}
              size="small"
              onChange={(e) => setUsername_search(e.target.value)}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_user_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_user_dialog_show("change")}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "69.7vw",
            }}
          >
            <Table
              dataSource={user_list}
              size="small"
              bordered
              columns={columns}
              rowKey="username"
              virtual
              scroll={{
                y: tableHeight,
              }}
              onRow={(record) => {
                return {
                  onClick: () => user_row_click(record), // 点击行
                };
              }}
              rowClassName={(record, index) => {
                if (record.username == clicked_username) {
                  return "row_clicked_style";
                }
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>

          {clicked_user_obj.role_grade ? (
            clicked_user_obj.role_grade <= 61 ? (
              <div className="manager_msg">
                {t("system_manager.manager_all_power")}
              </div>
            ) : (
              <>
                <div
                  className="noPage-table"
                  style={{
                    width: "14.9vw",
                  }}
                >
                  <Table
                    dataSource={user_com_list}
                    size="small"
                    bordered
                    columns={[
                      {
                        title: (ReactNode) => {
                          switch (clicked_user_obj.role_grade) {
                            case 70:
                              return t("system_manager.merchant");
                            case 80:
                              return t("system_manager.line");
                            default:
                              return t("system_manager.organization_name");
                          }
                        },
                        align: "center",
                        render: (_, record) => (
                          <>
                            {clicked_user_obj.role_grade === 70 ? (
                              <div>{record.mch}</div>
                            ) : clicked_user_obj.role_grade == 80 ? (
                              <div>{record.circuit}</div>
                            ) : (
                              <div>{record.com}</div>
                            )}
                          </>
                        ),
                      },
                    ]}
                    rowKey="com_id"
                    virtual
                    scroll={{
                      y: tableHeight,
                    }}
                    pagination={false}
                  />
                </div>
                <div
                  className="noPage-table"
                  style={{
                    width: "14.9vw",
                  }}
                >
                  <Table
                    dataSource={user_kind_list}
                    size="small"
                    bordered
                    columns={[
                      {
                        title: t("system_manager.kind_name"),
                        align: "center",
                        dataIndex: "name",
                      },
                    ]}
                    rowKey="id"
                    virtual
                    scroll={{
                      y: tableHeight,
                    }}
                    pagination={false}
                  />
                </div>
              </>
            )
          ) : (
            <div></div>
          )}
        </div>
      </div>
      <EditUser
        edit_user_title={edit_user_title}
        edit_user_show={edit_user_show}
        setEdit_user_show={setEdit_user_show}
        search_data={search_data}
        edit_type={edit_type}
        role_list={role_list}
        kind_list={kind_list}
        com_list={com_list}
        mch_list={mch_list}
        circuit_list={circuit_list}
        local_company_object={local_company_object}
        clicked_user_obj={clicked_user_obj}
        user_com_list={user_com_list}
        user_kind_list={user_kind_list}
      />
    </>
  );
}
